# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql  # pip install pymysql


# 处理京东评论的pipeline
class JDCommentsPipeline:
    # 可以将一些建立连接的过程放入该方法
    # 构造方法只会执行一次
    def __init__(self):
        # 建立连接
        self.conn = pymysql.connect(host='master', port=3306, user='root', password='123456', db='ScrapyDemo')

    def process_item(self, item, spider):
        id = item['id']
        nickname = item['nickname']
        score = item['score']
        content = item['content']
        productColor = item['productColor']
        creationTime = item['creationTime']
        # 创建游标
        with self.conn.cursor() as cursor:
            try:
                cursor.execute("insert into JDComments values(%s,%s,%s,%s,%s,%s)",
                               (id, nickname, score, content, productColor, creationTime))
            except Exception as e:
                print("#" * 30)
                print(e)
                print("#" * 30)
                self.conn.rollback()
            else:
                self.conn.commit()
        return item

    # 爬虫结束时会执行
    def close_spider(self, spider):
        self.conn.close()


# 处理京东评论的pipeline
class DouBanMoviesPipeline:
    def process_item(self, item, spider):
        return item
